import React, { useEffect, useState, Component } from "react";
import { View, Swiper, SwiperItem, Image } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { AtNavBar } from "taro-ui";
import { NavBottomBar } from "../../components";
import { useDispatch, useSelector } from "react-redux";
import { addToCarActionCreator } from "../../actions/car";
const Detail = () => {
  const [detail, setDetail] = useState({});
  const dispatch = useDispatch();
  const fetchDetail = async (id) => {
    const resp = await Taro.request({
      url: "http://localhost:3000/list/" + id,
    });
    console.log(resp.data);
    setDetail(resp.data);
  };
  const carList = useSelector((state) => state.car.carList);
  const totalCount = carList.reduce((p, n) => {
    return p + n.count;
  }, 0);

  const handleToCar = () => {
    // 加入购物车  dispatch(action)

    //
    dispatch(
      addToCarActionCreator({
        ...detail,
        count: 1,
        state: true,
      })
    );
  };

  useEffect(() => {
    const { id } = Taro.getCurrentInstance().router.params;
    fetchDetail(id);
  }, []);

  if (!detail.id) return <View>数据加载中...</View>;
  return (
    <View className="detail">
      {process.env.TARO_ENV === "h5" && (
        <AtNavBar
          color="#000"
          title="详情页"
          leftIconType="chevron-left"
          onClickLeftIcon={() => Taro.navigateBack()}
        />
      )}
      <Swiper className="banner" indicatorDots autoplay circular>
        {detail.image.map((v, i) => {
          return (
            <SwiperItem key={i}>
              <Image src={v}></Image>
            </SwiperItem>
          );
        })}
      </Swiper>
      {/* 商品信息 */}
      <View>
        <View className="title">{detail.title}</View>
        <View className="desc">{detail.desc}</View>
        <View className="price">{detail.price}</View>
      </View>

      {/* 底部提交兰 */}
      <NavBottomBar
        value={totalCount || ''}
        onCarIconClick={() =>
          /*进入购物车页面*/ Taro.switchTab({ url: "/pages/car/index" })
        }
        onLeftBtnClick={() => handleToCar()}
      ></NavBottomBar>
    </View>
  );
};

export default Detail;
